package com.fenghongzhang.broadcasttest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main4Activity extends AppCompatActivity {
    private TextView vName;
    private Button sendBC;

    private MyReceiver myReceiver;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            vName.setText(s);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        vName = (TextView) findViewById(R.id.v_name);

        sendBC = (Button) findViewById(R.id.sendBC);

        //动态注册
        myReceiver = new MyReceiver(handler);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.feng");
        registerReceiver(myReceiver,intentFilter);


        sendBC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置频道
                Intent intent = new Intent();
                intent.setAction("com.feng");

                //加数据
                Bundle bundle = new Bundle();
                bundle.putString("name","程小姐");
                intent.putExtras(bundle);

                sendBroadcast(intent);
            }
        });
    }
}
